package cn.summit.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Objects;


/**
 * 自定义决策器，在MyFilterSecurityInterceptor中注册
 *
 * @author summit
 * @since 2020/2/11 14:19
 */
@Service
@Slf4j
public class MyAccessDecisionManager implements AccessDecisionManager {

    /**
     * @param authentication UserService中循环添加到GrantedAuthority中的权限信息集合
     * @param object         包含客户端发起的请求的request信息，可以转换为HTTPRequest
     * @param collection     url所需的权限集合
     * @throws AccessDeniedException               访问拒绝异常
     * @throws InsufficientAuthenticationException
     */
    //此方法为框架模板方法
    //决策器 鉴定用户authentication是否有权访问
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        log.info("+++++++++++++++++++++决策");
        //collection为资源授权器提供的，被访问URL所需权限FilterInvocationSecurityMetadataSource
        //判断URL所需的权限集合是否为空，为空则放行
        if (null == collection || collection.size() <= 0) {
            log.debug("当前url无需权限");
            return;
        }
        FilterInvocation fi = (FilterInvocation) object;
//        log.info(fi.getRequestUrl());
//        log.info("当前用户[{}]",authentication.getName());
//        if (Objects.equals(authentication.getName(), "summit") && Objects.equals("/t2/update", fi.getRequestUrl())) {
//            log.info("特殊处理");
//            return;
//        }
        String needPermission;
        for (ConfigAttribute c : collection) {
            //获得所需的权限
            needPermission = c.getAttribute();
            //遍历用户拥有的权限进行对比
            for (GrantedAuthority ga : authentication.getAuthorities()) {
                if (needPermission.trim().equals(ga.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("无权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
